import axios from "axios";
import {useUserStore} from "@/stores/user.store.ts";
import {message} from "@/utils/message.ts";
import type {AxiosInstance, AxiosRequestConfig, InternalAxiosRequestConfig, AxiosError, AxiosResponse} from "axios";
import type {IApiResponse} from "@/types";


/**
 * 自定义封装请求方法
 * @param options 请求参数
 */
function request<T>(options: AxiosRequestConfig): Promise<IApiResponse<T>> {
    const userStore = useUserStore();

    const server: AxiosInstance = axios.create({
        baseURL: import.meta.env.VITE_API_DOMAIN,
        timeout: 6000,
        headers: {"Content-type": "application/json"}
    })

    /**
     * 请求拦截器
     */
    server.interceptors.request.use((config: InternalAxiosRequestConfig) => {

        if (config.headers) {
            config.headers.Authorization = "Bearer " + userStore.userToken.access;
        }

        return config;
    }, (error) => {

        return Promise.reject(error);
    });

    /**
     * 响应拦截器
     */
    server.interceptors.response.use((response: AxiosResponse) => {

        return response.data;
    }, (error: AxiosError) => {
        const responseData = error.response?.data as { message?: string } | undefined;
        switch (error.response?.status) {
            case 401:
                message.error(responseData?.message as string);
                break;
            case 403:
                message.error("fail 403");
                break;
            case 404:
                message.error(responseData?.message as string);
                break;
            case 500:
                break;
            default:
                break;
        }
        return Promise.reject(error);
    });

    return server.request(options);
}


// 请求函数导出
export default request;
